local mode_desc = [[
  # 酆都斗阴间模式简介

  ___

  总体规则类似欢乐斗地主（1v2模式）  
  游戏由3~6人进行，一人扮演阴间地主（主公），其余扮演人类农民（反贼），主公先进行行动。
  
  ## 地主增益：  
  1.专属阴间选将框。  
  2.增加一点体力上限和体力。  
  3.专属额外技能：  
  - **飞扬**：判定阶段开始时，你可以弃置两张手牌并弃置自己判定区内的一张牌。  
  - **跋扈**：锁定技，准备阶段，你摸一张牌；出牌阶段，你可以多使用一张杀。  
  

  ## 农民增益：  
  1.队友的手牌互相可见。  
  2.若游戏人数大于3，则从三号位到倒数第二位的农民获得技能“马术”。  
  3.当农民被击杀后，该农民选择一名队友，令其选择一个遗产：1.摸两张牌，2.或回复一点体力。  

  *任何人击杀农民没有摸三张牌的奖励。*  
  
  
  ## 胜利条件：  
  击败所有敌方阵营角色。
  
]]

-- 潘夏现版，石虎完全体，白起完全体，卫温诸葛直完全体，徐晃完全体，完全体刘渊，莎士比亚，初版韦诞，8上限初版王玄甫

local hell_generals = {
  "rfenghou_hell__luxun", -- 初版陆逊
  "rfenghou__hell_zhangxianzhong", -- 火伤用星无限制版大西王
  "rfenghou__huanwen", -- 欲霸8桓温
  "rfenghou__wangdun", -- 8上限王敦
  -- ↑这俩哥记得整个复制，换插图
}


-- Because packages are loaded before gamelogic.lua loaded
-- so we can not directly create subclass of gamelogic in the top of lua
local hell_combat_getLogic = function()
  local hell_combat_logic = GameLogic:subclass("hell_combat_logic")

  function hell_combat_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {nil, nil, {"lord", "rebel", "rebel"}}
    for i = 4, 8 do
      local ret = table.simpleClone(self.role_table[i-1])
      table.insert(ret, "rebel")
      self.role_table[i] = ret
    end
  end

  function hell_combat_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = room.settings.generalNum
    for _, p in ipairs(room.players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    local gameOver = function ()
      room:sendLog{ type = "#NoGeneralDraw", toast = true }
      room:gameOver("")
    end

    local lord = room:getLord()
    if lord == nil then gameOver() return end
    room:setCurrent(lord)
    local players = room.players
    
    local lord_generals = table.filter(hell_generals, function (g)
      return Fk.generals[g] ~= nil
    end)
    if #lord_generals == 0 then gameOver() return end

    lord_generals = table.random(lord_generals, generalNum)---@type string[]
    table.insert(lord_generals, "rfenghou__shibing")

    local nonlord = room:getOtherPlayers(lord)

    local generals = room:getNGenerals((#players - 1) * generalNum)
    local req = Request:new(players, "AskForGeneral")
    for _, p in ipairs(players) do
      local arg = {}
      if p.role == "lord" then
        arg = lord_generals
      else
        for _ = 1, generalNum do
          table.insert(arg, table.remove(generals))
        end
      end
      req:setData(p, { arg, 1 })
      req:setDefaultReply(p, { arg[#arg] })
    end
    req:ask()

    room:returnToGeneralPile(generals)
    for _, p in ipairs(players) do
      local general = req:getResult(p)[1]
      if p == lord then
        -- 预处理增益
        if general == "rfenghou__shibing" then
          local ex_generals = room:getNGenerals(generalNum)
          general = room:askForGeneral(p, ex_generals, 1)
          room:returnToGeneralPile(ex_generals)
        elseif general == "rfenghou__huanwen" then
          room:setPlayerMark(p, "@rfenghou__yuba", 8)
        end
      end
      room:prepareGeneral(p, general, "", true)
    end

    room:askForChooseKingdom(players)

    for _, p in ipairs(players) do
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "kingdom")
    end
    for _, p in ipairs(nonlord) do
      for _, p2 in ipairs(nonlord) do
        if p ~= p2 then
          p:addBuddy(p2)
        end
      end
    end
    room:setTag("SkipNormalDeathProcess", true)
  end


  function hell_combat_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players
  
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill.lordSkill then
        return
      end
      if #skill.attachedKingdom > 0 and not table.contains(skill.attachedKingdom, player.kingdom) then
        return
      end
  
      room:handleAddLoseSkills(player, skillName, nil, false)
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(p.role == "lord")) do
        addRoleModSkills(p, s)
      end
      if p.role == "lord" then
        room:handleAddLoseSkills(p, "m_feiyang|m_bahu", nil, false)
      else
        if p.seat > 2 and p.seat < (#room.players) then
          room:handleAddLoseSkills(p, "mashu", nil, false)
        end
      end
    end
  end

  return hell_combat_logic
end




local hell_combat_rule = fk.CreateTriggerSkill{
  name = "#hell_combat_rule",
  priority = 0.001,
  mute = true,
  events = {fk.BuryVictim},
  can_trigger = function(self, event, target, player, data)
    return target == player and target.rest == 0 and player.role == "rebel" and player.dead
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room.alive_players, function(p)
      return p.role == "rebel"
    end)
    if #targets == 0 then return end
    local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#hell_combat_bury-choose", "#hell_combat_bury", false)
    local to = room:getPlayerById(tos[1])
    local choices = {"draw2", "Cancel"}
    if to:isWounded() then
      table.insert(choices, 2, "hell_combat_heal")
    end
    local choice = room:askForChoice(to, choices, self.name)
    if choice == "draw2" then
      to:drawCards(2, self.name)
    else
      room:recover{ who = to, num = 1, skillName = self.name }
    end
  end,
}
Fk:addSkill(hell_combat_rule)

local hell_combat_mode = fk.CreateGameMode{
  name = "hell_combat_mode",
  minPlayer = 3,
  maxPlayer = 6,
  rule = hell_combat_rule,
  logic = hell_combat_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { }
    local room = Fk:currentRoom()
    local roles, friends = {}, {}
    for _, p in ipairs(room.players) do
      if p.rest > 0 or p:isAlive() then
        table.insertIfNeed(roles, p.role)
        if Self ~= p and p.role == Self.role then
          table.insert(friends, p)
        end
      end
    end

    return {
      { text = "hell_combat_mode_wincheck", passed = #roles < 3 and #friends == 0 }
    }
  end,
  get_adjusted = function (self, player)
    if player.role == "lord" then
      local exNum = 1
      if player.general == "rfenghou__wangdun" then
        exNum = 3
      end
      return {hp = player.hp + exNum, maxHp = player.maxHp + exNum}
    end
    return {}
  end
}


Fk:loadTranslationTable{
  ["hell_combat_mode"] = "酆都斗阴间",
  ["#hell_combat_rule"] = "游戏规则",
  ["#hell_combat_bury"] = "挑选遗产",
  ["#hell_combat_bury-choose"] = "请选择一名队友，令其获得遗产！（摸牌或回血）",
  ["hell_combat_heal"] = "回复1点体力",

  ["hell_combat_mode_wincheck"] = "无队友、第三方势力存活",

  [":hell_combat_mode"] = mode_desc,
}

return hell_combat_mode
